package com.cr.crsystem.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cr.crsystem.common.base.constant.CommonConstant;
import com.cr.crsystem.common.utils.OConvertUtils;
import com.cr.crsystem.common.utils.Result;
import com.cr.crsystem.system.entity.Car;
import com.cr.crsystem.system.entity.User;
import com.cr.crsystem.system.entity.UserRent;
import com.cr.crsystem.system.mapper.UserMapper;
import com.cr.crsystem.system.model.LoginModel;
import com.cr.crsystem.system.service.CarService;
import com.cr.crsystem.system.service.UserRentService;
import com.cr.crsystem.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author su
 * @since 2022-06-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRentService userRentService;
    @Autowired
    private CarService carService;

    @Override
    public User saveUser(User registerUser) {
        String salt = OConvertUtils.randomGen(8);
        registerUser.setSalt(salt);
        registerUser.setPassword(registerUser.getPassword());
        registerUser.setStatus(CommonConstant.USER_UNFREEZE);
        //step.1 保存用户
        this.save(registerUser);
        return registerUser;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Integer id) {
        User user = baseMapper.selectById(id);
        if (user != null) {
            baseMapper.deleteById(id);
            //删除用户汽车
            carService.remove(new QueryWrapper<Car>().lambda().eq(Car::getUserId, id));
            //删除用户订单
            List<UserRent> userRents = userRentService.list(new QueryWrapper<UserRent>().lambda().eq(UserRent::getUserId, id));
            List<Integer> rentIds = userRents.stream().map(UserRent::getRentId).collect(Collectors.toList());
            userRentService.remove(new QueryWrapper<UserRent>().in("rent_id", rentIds));
        }

        return false;
    }

    @Override
    public boolean editUser(User user) {
        String salt = OConvertUtils.randomGen(8);
        user.setSalt(salt);
        if(user.getSex().equals("男")) user.setSex("1");
        else if(user.getSex().equals("女")) user.setSex("0");
        baseMapper.updateById(user);
        return true;
    }

    @Override
    public Result<?> checkUserIsEffective(User user, LoginModel loginModel) {
        Result<Object> result = new Result<Object>();
        //情况1：根据用户信息查询，该用户不存在
        if (user == null) {
            result.error20001("该用户不存在，请注册");
            return result;
        }
        //情况2：根据用户信息查询，该用户已注销
        User deleteUser = baseMapper.selectById(user.getId());
        if (deleteUser == null) {
            result.error20001("该用户已注销");
            return result;
        }
        //情况3：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(user.getStatus())) {
            result.error20001("该用户已冻结");
            return result;
        }
        //情况4：校验用户名或密码是否正确
        if (!user.getPassword().equals(loginModel.getPassword())) {
            result.error20001("密码错误");
            return result;
        }
        return result;
    }

    @Override
    public boolean checkUsername(Integer userId, String username) {
        User user = null;
        if (userId==null) {
            user = baseMapper.selectById(userId);
        }
        User oldUser = null;
        if (!StringUtils.isEmpty(username)) {
            oldUser = baseMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        }
        //传入的username查询到信息了，需要判断是新增还是修改
        if (oldUser != null) {
            //user为空=>新增模式=>只要user存在则返回
            if (user == null) {
                return true;
            } else if (!userId.equals(oldUser.getId())) {
                //否则=>编辑模式=>判断两者ID是否一致
                return true;
            }
        }
        return false;
    }
}
